﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Accounts;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using System.Linq;

namespace mozhi.smarterp.Finance.Basedatas
{
    public class DataAssociationRepository : EfCoreRepository<FinanceDbContext, DataAssociation, Guid>, IDataAssociationRepository
    {
        public DataAssociationRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<DataAssociation>> FindAsync(DataAssociationQuery query)
        {
            var datas = await DbContext.Set<DataAssociation>().AsNoTracking()
              .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.OccupantCode.Contains(query.Keyword) || x.OccupantName.Contains(query.Keyword) || x.OccupiedCode.Contains(query.Keyword)
              || x.OccupiedName.Contains(query.Keyword))
              .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
              .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
              .WhereIf(query.OccupantId.HasValue, x => x.OccupantId == query.OccupantId)
              .WhereIf(query.OccupiedId.HasValue, x => x.OccupiedId == query.OccupiedId)
              .WhereIf(!query.OccupiedType.IsNullOrEmpty(), x => x.OccupiedType == query.OccupiedType)
              .ToListAsync();

            return datas;
        }

        public async Task<int> GetCountAsync(DataAssociationQuery query)
        {
            var count = await DbContext.Set<DataAssociation>().AsNoTracking()
            .WhereIf(!query.Keyword.IsNullOrEmpty(), x => x.OccupantCode.Contains(query.Keyword) || x.OccupantName.Contains(query.Keyword) || x.OccupiedCode.Contains(query.Keyword)
            || x.OccupiedName.Contains(query.Keyword))
            .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
            .WhereIf(query.Activated.HasValue, x => x.Activated == query.Activated.Value)
            .WhereIf(query.OccupantId.HasValue, x => x.OccupantId == query.OccupantId)
            .WhereIf(query.OccupiedId.HasValue, x => x.OccupiedId == query.OccupiedId)
            .WhereIf(!query.OccupiedType.IsNullOrEmpty(), x => x.OccupiedType == query.OccupiedType)
            .CountAsync();

            return count;
        }
    }
}
